package com.bodacn.storagescan;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.concurrent.locks.ReentrantLock;

public class StorageActivity extends AppCompatActivity implements View.OnClickListener {
    private String TAG = this.getClass().getName();
    private final static int MSG_AllowScan=9000;
    private final static int MSG_ScanBarcodeOver=9001;
    private final static int MSG_Detail =9002;
    private final static int MSG_ERROR=9003;
    TextView txt_titleInv, tv_barcodeCaption,tv_ResultInfo;
    FrameLayout liner_title;
    Button btn_Query,btn_Clear;
    ImageButton btn_return;
    EditText edit_Barcode;
    String serviceUrl="http://192.168.10.12/tvservice";
    String serviceUrlExt  = "/BDService.asmx?wsdl";
    String curLoginUserNo,curLoginUser,curLoginTime;//操作员所属部门等信息;
    String FormType="",Caption="",PrBarcode="",PrHouseDeID="",PrPartName="";
    JSONArray detailJSON;
    int pageItemCount=8;
    boolean ScanSign=false;
    ListView list_Order;
    Button btn_refreshDetail;
    //拦截扫描枪输入部分
    String BarcodeStr="";
    //全局变量
    Toast curToast;
    ScannerManager scannerManager;
    ReentrantLock reentrantLock = new ReentrantLock();
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (scannerManager.dispatchKeyEvent(event)) {
            return true;
        }
        return super.dispatchKeyEvent(event);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_storage);
        InitView();
        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo=paramBundle.getString("LoginUserNo");
        curLoginUser=paramBundle.getString("LoginUser");
        curLoginTime=paramBundle.getString("LoginTime");
        serviceUrl=paramBundle.getString("serviceUrl");
        serviceUrlExt=paramBundle.getString("serviceUrlExt");
        FormType=paramBundle.getString("FormType");
        Caption=paramBundle.getString("Caption");
        System.out.println("Caption:"+Caption);
        //界面变量
        ((TextView)findViewById(R.id.tv_userName)).setText("用户:"+curLoginUser);
        //置标题颜色
        txt_titleInv.setText(Caption);
        //拦截扫描事件
        scannerManager = new ScannerManager(new ScannerManager.OnScanListener() {
            @Override
            public void onResult(String code) {
                Log.d(TAG, "code= " + code);
                playRingtone();
                edit_Barcode.setText(code);
                ScanBarcode(edit_Barcode.getText().toString(),0);
            }
        });
        //初始提醒;
        curToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
    }


    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(this, notification);
        r.play();

    }


    //判断是否为数字，不然不转
    public static boolean isNumer(String str) {
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    private void InitView(){

        list_Order=findViewById(R.id.list_Order);
        list_Order.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            }
        });
        btn_Clear=findViewById(R.id.btn_Clear);
        btn_Clear.setOnClickListener(this);
        btn_Query=findViewById(R.id.btn_Scan);
        btn_Query.setOnClickListener(this);
        tv_ResultInfo=findViewById(R.id.tv_ResultInfo);
        btn_refreshDetail=findViewById(R.id.btn_refreshDetail);
        btn_refreshDetail.setOnClickListener(this);
        edit_Barcode=findViewById(R.id.edit_Barcode);
        edit_Barcode.setInputType(InputType.TYPE_NULL);
        edit_Barcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                edit_Barcode.setInputType(InputType.TYPE_CLASS_TEXT);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edit_Barcode,InputMethodManager.SHOW_FORCED);
            }
        });
        edit_Barcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    //Log.e("Debug","-----------------------------Debug-----------------------------");
                    //System.out.println(event);
                    if ((event.getAction()==KeyEvent.ACTION_UP)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        //System.out.println(edit_Barcode.getText().toString());
                        ScanBarcode(edit_Barcode.getText().toString(),0);
                        return true;
                    }
                }
                return false;
            }
        });
        edit_Barcode.requestFocus();
        edit_Barcode.requestFocusFromTouch();
        liner_title=findViewById(R.id.liner_title);
        tv_barcodeCaption =findViewById(R.id.tv_barcodeCaption);
        txt_titleInv=findViewById(R.id.txt_titleInv);
        btn_return =findViewById(R.id.btn_return);
        btn_return.setOnClickListener(this);

    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onClick(View view) {
        hideIM(view);
        switch (view.getId()){
            case R.id.btn_Clear:
                //mediaPlayer.start();
                final String TrayCode=((EditText)findViewById(R.id.edt_TrayCode)).getText().toString();
                if (TrayCode.length()>0) {
                    AlertDialog alertDialog = new AlertDialog.Builder(this)
                            .setTitle(getString(R.string.SystemHint)).setMessage("您确定要清空托盘上的所有数据？")
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    hideIM(edit_Barcode);
                                    edit_Barcode.selectAll();
                                    edit_Barcode.requestFocus();
                                    ClearTrayData(TrayCode);
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                } else{
                    curToast.setText("请先扫描托盘条码!");
                    curToast.show();
                }
                break;
            case R.id.btn_return:
                finish();//关闭当前Activity，返回上一级;
                break;
            case R.id.btn_Scan:
                if ((edit_Barcode.getText()!=null)&&(edit_Barcode.getText().length()>0)) {
                     ScanBarcode(edit_Barcode.getText().toString(),0);
                } else Toast.makeText(getApplicationContext(),"请先输入条码!",Toast.LENGTH_LONG).show();
                break;
            case R.id.btn_refreshDetail:
                ScanBarcodeDetail(PrBarcode);
                hideIM(liner_title);
                break;
            default:
                break;
        }
    }

    private void ClearTrayData(String TrayCode) {
        //组织WebService地址;
        String SqlComm="Exec App_AgvScanBarcodeDetail @Barcode='"+TrayCode+"',@FormType='"+FormType+"',@PrBarcode='"+(PrBarcode)
                + "',@TrayCode='" + (((EditText) findViewById(R.id.edt_TrayCode)).getText())
                + "',@StyleNo='" + (((EditText) findViewById(R.id.edt_StyleNo)).getText())
                +"',@OperType='ClearTray',@UserNo='" + curLoginUserNo+ "',@UserName='"+curLoginUser+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    //登陆校验;
    private void ScanBarcode(String paramBarcode,int inProgress){
        hideIM(edit_Barcode);
        //刷新表格
        try {
            detailJSON = new JSONArray("[]");
            DetailGridAdapter detailGridAdapter = new DetailGridAdapter(getApplicationContext());
            detailGridAdapter.jsonArray = detailJSON;
            list_Order.setAdapter(detailGridAdapter);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        String SqlComm = "Exec App_AgvScanBarcode @Barcode='" + paramBarcode + "',@FormType='" + FormType + "',@PrBarcode='" + (PrBarcode)
                + "',@TrayCode='" + (((EditText) findViewById(R.id.edt_TrayCode)).getText())
                + "',@StyleNo='" + (((EditText) findViewById(R.id.edt_StyleNo)).getText())
                + "',@OperType='ScanBarcode',@UserNo='" + curLoginUserNo
                + "',@UserName='"+curLoginUser+"'";
        PrBarcode = paramBarcode;
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    //刷新校验;
    private void ScanBarcodeDetail(String paramBarcode){
        //组织WebService地址;
        String SqlComm="Exec App_AgvScanBarcodeDetail @Barcode='"+paramBarcode+"',@FormType='"+FormType
                +"',@PrBarcode='"+(PrBarcode)
                + "',@TrayCode='" + (((EditText) findViewById(R.id.edt_TrayCode)).getText())
                + "',@StyleNo='" + (((EditText) findViewById(R.id.edt_StyleNo)).getText())
                +"',@OperType='ScanDetail',@UserNo='" + curLoginUserNo+ "',@UserName='"+curLoginUser+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }


    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            Bundle bundle=msg.getData();
            hideIM(edit_Barcode);
            edit_Barcode.setEnabled(true);
            edit_Barcode.selectAll();
            edit_Barcode.requestFocus();
            ScanSign=false;
            switch (msgId) {
                case MSG_ERROR:
                    String HintInfo=bundle.getString("HintInfo");
                    curToast.setText(HintInfo);
                    curToast.show();
                    break;
                case MSG_Detail:
                    if (detailJSON != null&&detailJSON.length()>0) {
                        System.out.println("MSG_Detail:-"+detailJSON.toString());
                        if (detailJSON.optJSONObject(0).has("ResultInfo")) {
                            try {
                                ((TextView) findViewById(R.id.tv_ResultInfo)).setText(detailJSON.optJSONObject(0).getString("ResultInfo"));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        //刷新表格
                        (findViewById(R.id.horizontalScroll)).scrollTo(0, 0);
                        DetailGridAdapter detailGridAdapter = new DetailGridAdapter(getApplicationContext());
                        detailGridAdapter.jsonArray = detailJSON;
                        list_Order.setAdapter(detailGridAdapter);
                    }
                    break;
                case MSG_ScanBarcodeOver:
                    if (detailJSON != null) {
                        //填充屏幕
                        fillScreen(detailJSON.optJSONObject(0));
                    }

                    break;
                case MSG_AllowScan:
                    ScanSign=false;
                    break;
                default:
                    break;
            }
        }
    };

    private void fillScreen(JSONObject optJSONObject) {
        if (optJSONObject!=null){
            try {
                ((HorizontalScrollView)findViewById(R.id.horizontalScroll)).scrollTo(0,0);
                if (optJSONObject.has("TrayCode")) ((EditText) findViewById(R.id.edt_TrayCode)).setText(optJSONObject.getString("TrayCode"));
                if (optJSONObject.has("StyleNo")) ((EditText) findViewById(R.id.edt_StyleNo)).setText(optJSONObject.getString("StyleNo"));
                if (optJSONObject.has("MaterialName")) ((EditText) findViewById(R.id.edt_MaterialName)).setText(optJSONObject.getString("MaterialName"));
                if (optJSONObject.has("ExchangeBarcode")) ((TextView) findViewById(R.id.edt_ExchangeBarcode)).setText(optJSONObject.getString("ExchangeBarcode"));
                if (optJSONObject.has("PieceNo")) ((TextView) findViewById(R.id.edt_PieceNo)).setText(optJSONObject.getString("PieceNo"));
                if (optJSONObject.has("BowlNo")) ((TextView) findViewById(R.id.edt_BowlNo)).setText(optJSONObject.getString("BowlNo"));
                if (optJSONObject.has("PackValue")) ((TextView) findViewById(R.id.txt_PackValue)).setText(optJSONObject.getString("PackValue"));
                if (optJSONObject.has("ResultInfo")) ((TextView) findViewById(R.id.tv_ResultInfo)).setText(optJSONObject.getString("ResultInfo"));
                if (optJSONObject.has("ErrInfo") == true) {
                    //MediaPlayer mediaPlayer = MediaPlayer.create(getActivity(), R.raw.warn);
                    //mediaPlayer.start();
                    AlertDialog alertDialog = new AlertDialog.Builder(this)
                            .setTitle(getString(R.string.SystemHint)).setMessage(optJSONObject.getString("ErrInfo"))
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    hideIM(edit_Barcode);
                                    edit_Barcode.selectAll();
                                    edit_Barcode.requestFocus();
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                }
                if (optJSONObject.has("HaveDetail")){
                    //刷新表格
                    DetailGridAdapter detailGridAdapter = new DetailGridAdapter(getApplicationContext());
                    detailGridAdapter.jsonArray = detailJSON;
                    list_Order.setAdapter(detailGridAdapter);
                }
                if (optJSONObject.has("GetDetail")){
                   if (optJSONObject.getString("GetDetail").equals("Y"))  ScanBarcodeDetail(PrBarcode);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        ScanSign=true;
        Runnable run = new Runnable() {
            @Override
            public synchronized void run() {
                try{
                    reentrantLock.lock();
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    ScanSign=false;
                    //往界面转数据;
                    String OperType="";
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        if (jsonArray.optJSONObject(0).has("OperType"))
                            OperType=jsonArray.optJSONObject(0).getString("OperType");
                        if (jsonArray.optJSONObject(0).has("OPERTYPE"))
                            OperType=jsonArray.optJSONObject(0).getString("OPERTYPE");
                        if (OperType.equals("ScanBarcode")==true||OperType.equals("ClearTray")==true){
                            detailJSON=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_ScanBarcodeOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        if (OperType.equals("ScanDetail")==true){
                            detailJSON=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_Detail;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        if (jsonArray.optJSONObject(0).has("SQLExcept") == true) {
                            //刷新界面;
                            Message errmsg = new Message();
                            Bundle bundle = new Bundle();
                            bundle.putString("HintInfo", jsonArray.optJSONObject(0).getString("SQLMessage"));
                            errmsg.what = MSG_ERROR;
                            errmsg.setData(bundle);
                            handler.removeMessages(errmsg.what);
                            handler.sendMessage(errmsg);
                        }
                    } else {
                        //刷新界面;
                        Message errmsg = new Message();
                        Bundle bundle = new Bundle();
                        bundle.putString("HintInfo", "未返回任何数据!");
                        errmsg.what = MSG_ERROR;
                        errmsg.setData(bundle);
                        handler.removeMessages(errmsg.what);
                        handler.sendMessage(errmsg);
                    }
                } catch (Exception e) {
                    //刷新界面;
                    Message errmsg = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putString("HintInfo", e.getMessage());
                    errmsg.what = MSG_ERROR;
                    errmsg.setData(bundle);
                    handler.removeMessages(errmsg.what);
                    handler.sendMessage(errmsg);
                    reentrantLock.unlock();
                }finally {
                    reentrantLock.unlock();
                }

            }

        };
        new Thread(run).start();

    }



    //订单表格适配器;
    public final class DetailGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        private JSONArray jsonArray;

        @Override
        public int getCount() {
            return jsonArray.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return jsonArray.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.activity_storage_item, null, false);
            String tmpValue;
            //int pullVatListWidth=parent.getWidth();
            //convertView.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,45));
            int backcolor=getResources().getColor(R.color.white);
            int fontcolor=getResources().getColor(R.color.text_black);
            if (position%2==1) backcolor=getResources().getColor(R.color.listContentColor);
            try {
                if (jsonArray.optJSONObject(position).has("ConColor")==true) {
                    tmpValue = jsonArray.optJSONObject(position).getString("ConColor");
                    backcolor=GetColorValue(tmpValue);
                }
                if (jsonArray.optJSONObject(position).has("ConFontColor")==true) {
                    tmpValue = jsonArray.optJSONObject(position).getString("ConFontColor");
                    fontcolor=GetColorValue(tmpValue);
                }
                TextView tv = convertView.findViewById(R.id.tv_StyleNo);// 显示文字
                if (jsonArray.optJSONObject(position).has("StyleNo")==true) {
                    tv.setText(jsonArray.optJSONObject(position).getString("StyleNo"));
                }
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_MaterialName);// 显示文字
                if (jsonArray.optJSONObject(position).has("MaterialName")==true)
                    tv.setText(jsonArray.optJSONObject(position).getString("MaterialName"));
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_Number);// 显示文字
                if (jsonArray.optJSONObject(position).has("Number")==true)
                    tv.setText(jsonArray.optJSONObject(position).getString("Number"));
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_Uint);// 显示文字
                if (jsonArray.optJSONObject(position).has("Uint")==true){
                    tv.setText(jsonArray.optJSONObject(position).getString("Uint"));
                }
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_NumberAssist);// 显示文字
                if (jsonArray.optJSONObject(position).has("NumberAssist")==true){
                    tv.setText(jsonArray.optJSONObject(position).getString("NumberAssist"));
                }
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_UintAssist);// 显示文字
                if (jsonArray.optJSONObject(position).has("UintAssist")==true){
                    tv.setText(jsonArray.optJSONObject(position).getString("UintAssist"));
                }
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_ExchangeBarcode);// 显示文字
                if (jsonArray.optJSONObject(position).has("ExchangeBarcode")==true){
                    tv.setText(jsonArray.optJSONObject(position).getString("ExchangeBarcode"));
                }
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailGridAdapter_position:"+position);
            return convertView;
        }

    }



    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()==7)){
            int testColor=Integer.parseInt(StrPenColor.substring(1),16);
            int red = (testColor & 0xff0000) >> 16;
            int green = (testColor & 0x00ff00) >> 8;
            int blue = (testColor & 0x0000ff);
            PenColor=Color.rgb(red, green, blue);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }



}
